package handlers

import (
	"book-manage/cache"
	"book-manage/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func List(c *gin.Context) {
	var book []models.Book
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": book,
		"msg":  "ok",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var book []models.Book
	redis_key := "detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": book,
		"msg":  "ok",
	})
	return
}
